package com.u.social.sale.mq;

/**
 * @program: awesome-spring
 * @description: 消费者
 * @author: Alex Wu
 * @createDate: 2025-02-11 09:43
 **/
import com.u.social.sale.service.IOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RocketMQMessageListener(topic = "secKill-topic", consumerGroup = "secKill-topic-group",
        maxReconsumeTimes = 3)  // 配置死信队列最好配置最大消费次数，否则按照16次计算
public class RocketMQConsumer implements RocketMQListener<String> {

    @Autowired
    private IOrderService orderService;


    @Override
    public void onMessage(String message) {
        System.out.println("Received message: " + message);

        String[] split = message.split(":");
        if(split.length != 2){
            throw new RuntimeException("Over Simulated failure");
        }

        Long userId = Long.parseLong(split[0]);
        Long productId = Long.parseLong(split[0]);
        System.out.println("userId:" + userId + ",productId:" + productId);

        Boolean isOrderd = orderService.addOrderByProduct(productId, null);
        if(!isOrderd){  // 失败后放入死信队列，采取重试的方式
            throw new RuntimeException("enter the Dead Topic");
        }

        // 或者不重试，直接增加 Redis 库存原子操作
        /*if(!isOrderd){
            redisTemplate.opsForValue().set("REDIS_KEY_PREFIX" + productId , StockNum + 1);
        }*/
    }
}

